package org.example.hospital_frontend.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.example.hospital_frontend.common.Result;
import org.example.hospital_frontend.domain.MedicalRecord;
import org.example.hospital_frontend.domain.Register;
import org.example.hospital_frontend.domain.MedicalRecordVO;
import org.example.hospital_frontend.service.MedicalRecordService;
import org.example.hospital_frontend.service.RegisterService;
import org.example.hospital_frontend.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;

@RestController
@RequestMapping("/medical")
public class MedicalRecordController {

    @Autowired
    private MedicalRecordService medicalRecordService;

    @Autowired
    private RegisterService registerService;

    @Autowired
    private UserService userService;

    // 获取病历列表（支持分页和简单搜索）
    @GetMapping("/admin/list")
    public Result<Page<MedicalRecordVO>> getMedicalRecordList(
            @RequestParam(defaultValue = "1") Integer pageNum,
            @RequestParam(defaultValue = "10") Integer pageSize,
            @RequestParam(required = false) String keyword) {

        Page<MedicalRecordVO> page = medicalRecordService.getMedicalRecordVOPage(new Page<MedicalRecordVO>(pageNum, pageSize), keyword);

        return Result.success(page);
    }

    // 删除病历
    @DeleteMapping("/admin/{id}")
    public Result deleteMedicalRecord(@PathVariable Integer id) {
        medicalRecordService.removeById(id);
        return Result.success();
    }

    // 添加病历
    @PostMapping("/admin/add")
    public Result addMedicalRecord(@RequestBody MedicalRecord medicalRecord) {
        medicalRecordService.save(medicalRecord);
        Integer id = medicalRecord.getRegisterId();
        //添加过后，挂号信息显示为已就诊
        Register register = registerService.getById(id);
        register.setStatus(1L);
        registerService.updateById(register);
        return Result.success();
    }

    // 更新病历
    @PostMapping("/admin/update")
    public Result updateMedicalRecord(@RequestBody MedicalRecord medicalRecord) {
        medicalRecordService.updateById(medicalRecord);
        return Result.success();
    }

    // 获取病历详情
    @GetMapping("/admin/{id}")
    public Result<MedicalRecord> getMedicalRecordById(@PathVariable Integer id) {
        MedicalRecord medicalRecord = medicalRecordService.getById(id);
        return Result.success(medicalRecord);
    }

    /**
     * 获取当前登录患者的病历列表
     *
     * @param request HttpServletRequest
     * @return 患者病历列表
     */
    @GetMapping("/user/list")
    public Result getUserMedicalRecordList(HttpServletRequest request) {
        org.example.hospital_frontend.domain.User currentUser = (org.example.hospital_frontend.domain.User) request.getSession().getAttribute("USER_LOGIN_STATE");
        if (currentUser == null) {
            return Result.error("无权限");
        }

        QueryWrapper<org.example.hospital_frontend.domain.Register> registerQueryWrapper = new QueryWrapper<>();
        registerQueryWrapper.eq("user_id", currentUser.getId());
        java.util.List<org.example.hospital_frontend.domain.Register> registerList = registerService.list(registerQueryWrapper);

        if (registerList.isEmpty()) {
            return Result.success(java.util.Collections.emptyList()); // 没有挂号记录，返回空列表
        }

         java.util.List<Integer> registerIds = registerList.stream()
                                                .map(org.example.hospital_frontend.domain.Register::getId)
                                                .collect(java.util.stream.Collectors.toList());

        java.util.List<org.example.hospital_frontend.domain.MedicalRecordVO> medicalRecordVOList = new java.util.ArrayList<>();
        for (org.example.hospital_frontend.domain.Register register : registerList) {
             // 根据 registerId 查询对应的 MedicalRecord
             QueryWrapper<org.example.hospital_frontend.domain.MedicalRecord> mrWrapper = new QueryWrapper<>();
             mrWrapper.eq("register_id", register.getId());
             org.example.hospital_frontend.domain.MedicalRecord medicalRecord = medicalRecordService.getOne(mrWrapper);

             if (medicalRecord != null) {
                 org.example.hospital_frontend.domain.MedicalRecordVO medicalRecordVO = new org.example.hospital_frontend.domain.MedicalRecordVO();
                 medicalRecordVO.setRegisterTime(register.getRegisterTime());
                 org.springframework.beans.BeanUtils.copyProperties(medicalRecord, medicalRecordVO);

                 // 获取医生姓名
                 org.example.hospital_frontend.domain.User doctor = userService.getById(register.getDoctorId());
                  if (doctor != null) {
                      medicalRecordVO.setDoctorUsername(doctor.getUsername());
                  }
                 medicalRecordVOList.add(medicalRecordVO);
             }
        }


        return Result.success(medicalRecordVOList);
    }

    /**
     * 获取当前登录患者的指定病历详情
     * @param id 病历ID
     * @param request HttpServletRequest
     * @return 病历详情 MedicalRecordVO
     */
    @GetMapping("/user/{id}")
    public Result<MedicalRecordVO> getUserMedicalRecordDetail(@PathVariable Integer id, HttpServletRequest request) {
        // 检查用户是否登录且为患者 (role = 0)
        org.example.hospital_frontend.domain.User currentUser = (org.example.hospital_frontend.domain.User) request.getSession().getAttribute("USER_LOGIN_STATE");
        if (currentUser == null ) {
            return Result.error("无权限");
        }

        // 检查病历是否存在并获取详情 (包含医生姓名)
        // 调用 MedicalRecordMapper 中新加的 selectMedicalRecordVOById 方法
        MedicalRecordVO medicalRecordVO = medicalRecordService.getMedicalRecordVOById(id); // TODO: 在 MedicalRecordService 中实现此方法

        if (medicalRecordVO == null) {
             return Result.error("病历不存在");
        }

        // 验证该病历是否属于当前患者
        // 根据病历的 registerId 获取对应的 Register 记录
        org.example.hospital_frontend.domain.Register relatedRegister = registerService.getById(medicalRecordVO.getRegisterId());

        if (relatedRegister == null || !relatedRegister.getUserId().equals(currentUser.getId())) {
             return Result.error("无权查看此病历");
        }

        return Result.success(medicalRecordVO);
    }

} 